package com.ruoyi.law.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageCondition;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.law.domain.dto.LawEarningRecordDTO;
import com.ruoyi.law.domain.dto.LawProfitDTO;
import com.ruoyi.law.domain.entity.LawCashOut;
import com.ruoyi.law.domain.entity.LawEarningRecord;
import com.ruoyi.law.domain.entity.LawOrder;
import com.ruoyi.law.enums.OutCashState;
import com.ruoyi.law.service.*;
import com.ruoyi.law.utils.UserUtil;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 收益记录 前端控制器
 * </p>
 *
 * @author code
 * @since 2022-11-28
 */
@Api(tags = "收益记录")
@RestController
@RequestMapping("/earningRecord")
public class LawEarningRecordController extends BaseController {
    @Autowired
    private ILawEarningRecordService earningRecordService;
    @Autowired
    private ILawServiceService serviceService;
    @Autowired
    private ILawTeamService teamService;
    @Autowired
    private ILawCashOutService cashOutService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ILawOrderService orderService;

    @ApiOperation("根据用户id查询收益记录")
    @GetMapping("/info")
    public R<Page<LawEarningRecordDTO>> info(PageCondition<LawEarningRecord> pageCondition, Long userId) {
        LambdaQueryWrapper<LawEarningRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LawEarningRecord::getUserId, userId);
        Page<LawEarningRecord> page = earningRecordService.page(pageCondition.toPage(), queryWrapper);
        List<LawEarningRecord> list = page.getRecords();

        List<LawEarningRecordDTO> dtoList = new ArrayList<>(list.size());
        for (LawEarningRecord earningRecord : list) {
            LawEarningRecordDTO earningRecordDTO = BeanUtil.toBean(earningRecord, LawEarningRecordDTO.class);
            earningRecordDTO.setUserName(UserUtil.getUserName(earningRecord.getUserId()));
            earningRecordDTO.setServiceName(
                    serviceService.getName(earningRecord.getServiceId(), earningRecord.getEarningType()));
            dtoList.add(earningRecordDTO);
        }
        Page<LawEarningRecordDTO> dtoPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        dtoPage.setRecords(dtoList);
        return R.ok(dtoPage);
    }

    @ApiOperation("根据收益id查询收益记录详情")
    @GetMapping("/detail")
    public R<LawEarningRecordDTO> detail(Long id) {
        LawEarningRecord earningRecord = earningRecordService.getById(id);
        LawEarningRecordDTO earningRecordDTO = BeanUtil.toBean(earningRecord, LawEarningRecordDTO.class);
        earningRecordDTO.setUserName(UserUtil.getUserName(earningRecord.getUserId()));
        earningRecordDTO.setServiceName(serviceService.getName(earningRecord.getServiceId(),
                earningRecord.getEarningType()));
        // 收益来源
        String num = earningRecordDTO.getNum();
        LawOrder lawOrder = orderService.getByOrderNum(num);
        if (lawOrder != null) {
            // 收益来源用户名称
            Long uid = lawOrder.getUid();
            SysUser user = userService.selectUserById(uid);
            if (user != null) {
                earningRecordDTO.setUserName(user.getNickName());
                earningRecordDTO.setUserAvatarFrom(user.getAvatar());
            }
        }

        return R.ok(earningRecordDTO);
    }

    @ApiOperation("根据团队id查询提成记录")
    @ApiImplicitParam(name = "teamId", value = "团队id(律师团队id)", required = true)
    @GetMapping("/teamInfo")
    public R<Page<LawEarningRecordDTO>> teamInfo(PageCondition<LawEarningRecord> pageCondition, Long teamId) {
        LambdaQueryWrapper<LawEarningRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LawEarningRecord::getUserId, teamId);
        Page<LawEarningRecord> page = earningRecordService.page(pageCondition.toPage(), queryWrapper);
        List<LawEarningRecord> list = page.getRecords();

        List<LawEarningRecordDTO> dtoList = new ArrayList<>(list.size());
        for (LawEarningRecord earningRecord : list) {
            LawEarningRecordDTO earningRecordDTO = BeanUtil.toBean(earningRecord, LawEarningRecordDTO.class);
            earningRecordDTO.setUserName(teamService.getById(earningRecord.getUserId()).getName());
            earningRecordDTO.setServiceName(
                    serviceService.getName(earningRecord.getServiceId(), earningRecord.getEarningType()));
            dtoList.add(earningRecordDTO);
        }
        Page<LawEarningRecordDTO> dtoPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        dtoPage.setRecords(dtoList);
        return R.ok(dtoPage);
    }

    @ApiOperation("获取当前用户总收益、可用余额、冻结余额、已提现金额")
    @GetMapping("/getMoney")
    public R<LawProfitDTO> getMoney() {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        SysUser user = userService.selectUserById(userId);
        // 可用余额
        BigDecimal amount = user.getAmount() == null ? BigDecimal.ZERO : user.getAmount();
        // 冻结余额
        BigDecimal amountFrozen = user.getAmountFrozen() == null ? BigDecimal.ZERO : user.getAmountFrozen();
        // 已提现金额
        List<LawCashOut> cashOutList = cashOutService.lambdaQuery()
                .eq(LawCashOut::getUserId, user.getUserId())
                .eq(LawCashOut::getState, OutCashState.agree.getValue())
                .list();
        BigDecimal amountWithdraw = cashOutList.stream()
                .map(LawCashOut::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        // 总收益
        BigDecimal total = amount.add(amountFrozen).add(amountWithdraw);
        LawProfitDTO profitDTO = new LawProfitDTO()
                .setAmount(amount)
                .setAmountFrozen(amountFrozen)
                .setAmountWithdraw(amountWithdraw)
                .setTotal(total);
        return R.ok(profitDTO);
    }

}
